# -*- coding: utf-8 -*-
from odoo import models, api, fields, tools
from odoo.exceptions import UserError
import re


class doc_category(models.Model):

    _name = "proman.doc_category"
    _rec_name = "complete_name"
    _description = "文档类型"
    _table = "proman_doc_category"
    _parent_name = "parent_id"
    _parent_store = True
    _order = "sequence"

    sequence = fields.Integer(string="排序",translate = 0)
    name = fields.Char(string="文档类型",help = '请输入文档类型',required = 1,translate = 0)
    company_id = fields.Many2one(string="所属公司",comodel_name = 'res.company',default = lambda self:self.env.company,required = 1,translate = 0)
    parent_id = fields.Many2one(string="上级类别",comodel_name = 'proman.doc_category',translate = 0)
    child_id = fields.One2many(string="子类别",comodel_name = 'proman.doc_category',inverse_name = 'parent_id',readonly = 1,translate = 0)
    complete_name = fields.Char(string="完整路径名",compute = '_compute_complete_name',store = 1,translate = 0)
    parent_path = fields.Char(string="父路径",index = 1,translate = 0)
    level = fields.Integer(string="层级",compute = '_compute_level',store = 1,translate = 0)
    memo = fields.Html(string="备注说明",translate = 0)
    _sql_constraints =  [
        ('name_uniq', 'unique (parent_id,name)', '同类别下名称相同'),       ]

    @api.depends('name', 'parent_id.complete_name')
    def _compute_complete_name(self):
        for category in self:
            if category.parent_id:
                category.complete_name = '%s / %s' % (category.parent_id.complete_name, category.name)
            else:
                category.complete_name = category.name
    @api.depends("parent_path")
    def _compute_level(self):
        for rc in self:
            if rc.parent_path:
                rc.level = str(rc.parent_path).count("/")
            else:
                rc.level = 0
    def name_get(self):
        if not self.env.context.get('hierarchical_naming', True):
            return [(record.id, record.name) for record in self]
        return super(doc_category, self).name_get()

